package com.jsyh.maidu.activity.me;

import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.jsyh.maidu.R;
import com.jsyh.maidu.activity.MainActivity;
import com.jsyh.maidu.alipay.PayResult;
import com.jsyh.maidu.model.AliPatModel;
import com.jsyh.maidu.model.OrderSubmitMsg;
import com.jsyh.maidu.model.WXpayModel;
import com.jsyh.maidu.presenter.PayActivePresenter;
import com.jsyh.maidu.utils.Utils;
import com.jsyh.maidu.views.PayActiveView;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

public class SqPayThirdActivity extends Activity implements View.OnClickListener,PayActiveView{

    TextView tv_title,tv_price;
    ImageView iv_back;
    OrderSubmitMsg ordersubmitBean;
    private static final int SDK_PAY_FLAG = 1;

    private static final int SDK_CHECK_FLAG = 2;
    int payor=1;
    String aliinfo="";
    Button btn_pay;
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);

                    // 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
                    String resultInfo = payResult.getResult();

                    String resultStatus = payResult.getResultStatus();

                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        Intent intent=new Intent(SqPayThirdActivity.this, MainActivity.class);
                        startActivity(intent);
                        Utils.showToast(SqPayThirdActivity.this, "支付成功");
                    } else {
                        // 判断resultStatus 为非“9000”则代表可能支付失败
                        // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            Utils.showToast(SqPayThirdActivity.this,"支付结果确认中");
                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            Utils.showToast(SqPayThirdActivity.this, "支付失败");
                        }
                    }
                    break;
                }
                case SDK_CHECK_FLAG: {
                    if (!(boolean) msg.obj)
                        Utils.showToast(SqPayThirdActivity.this, "检查结果为：" + msg.obj);
                    else {

                    }
                    break;
                }
                default:
                    break;
            }
        };
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sq_pay_third);
        ordersubmitBean= (OrderSubmitMsg) getIntent().getSerializableExtra("orderMsg");
        InitView();

    }

    public void InitView()
    {
        payor=Integer.valueOf(getIntent().getStringExtra("payor"));


        tv_title= (TextView) findViewById(R.id.title);
        iv_back= (ImageView) findViewById(R.id.back);
        tv_price= (TextView) findViewById(R.id.tv_SQPT_price);
        btn_pay= (Button) findViewById(R.id.btn_SQPT_gopay);
        if (payor==0)
        {
            btn_pay.setText("完成");
        }else {
            btn_pay.setText("支付");
        }
        btn_pay.setOnClickListener(this);
        tv_title.setText("提交订单");
        tv_price.setText(ordersubmitBean.getData().getOrder_amount().toString());
        iv_back.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {

        switch (view.getId())
        {
            case R.id.back:
                finish();
                break;

            case R.id.btn_SQPT_gopay:
                if(payor==0){
                    Intent intent=new Intent(SqPayThirdActivity.this, MainActivity.class);
                    startActivity(intent);
                    Utils.showToast(SqPayThirdActivity.this, "订单完成 ");
                    finish();
                    return;
            }

                PayActivePresenter paypresenter=new PayActivePresenter(this,this,ordersubmitBean.getData(),getIntent().getStringExtra("sid"));
                if (String.valueOf(ordersubmitBean.getData().getPay_id()).equals("1"))
                {
                    paypresenter.LoadsqAliPay();

                }else
                {
                    paypresenter.LoadSQWXPay();
                }
                break;
        }
    }



    Runnable payRunnable = new Runnable() {

        @Override
        public void run() {
            PayTask alipay = new PayTask(SqPayThirdActivity.this);
            String result = alipay.pay(aliinfo);

            Message msg = new Message();
            msg.what = SDK_PAY_FLAG;
            msg.obj = result;
            mHandler.sendMessage(msg);
        }
    };

    @Override
    public void getWXinfo(WXpayModel wxpay) {
        if (wxpay.getCode().equals("1")) {
            final IWXAPI api = WXAPIFactory.createWXAPI(this, null);
            // 将该app注册到微信
            api.registerApp("wxb6b89ad7d9ebfbb0");

            PayReq req = new PayReq();

            req.appId = wxpay.getData().getPayinfo().getAppId();

            req.partnerId = wxpay.getData().getPayinfo().getPartnerId();
            req.prepayId = wxpay.getData().getPayinfo().getPrepayId();
            req.packageValue = "Sign=WXPay";
            req.nonceStr = wxpay.getData().getPayinfo().getNonceStr();
            req.timeStamp = wxpay.getData().getPayinfo().getTimeStamp();
            req.sign = wxpay.getData().getPayinfo().getSign();
            api.sendReq(req);


            finish();
        }else {
            Toast.makeText(this,wxpay.getMsg(),Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void getALiinfo(AliPatModel ali) {
        aliinfo=ali.getData().getPayinfo();
        Thread payThread = new Thread(payRunnable);
        payThread.start();

    }
}
